<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="goodsQuery.goodsNo" placeholder="物品号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="goodsQuery.goodsName" placeholder="物品名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="goodsQuery.begin" type="datetime" placeholder="开始时间" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="goodsQuery.end" type="datetime" placeholder="结束时间" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="物品编号" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.goodsNo }}
        </template>
      </el-table-column>
      <el-table-column label="物品名称" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.goodsName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物品价格" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="400">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.gmtCreate }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="修改时间">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.gmtModified }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="medium" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="medium" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="goods" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="物品编号" prop="goodsNo">
          <el-input v-model="goods.goodsNo" />
        </el-form-item>
        <el-form-item label="物品名称" prop="goodsName">
          <el-input v-model="goods.goodsName" />
        </el-form-item>
        <el-form-item label="物品价格" prop="price">
          <el-input v-model="goods.price" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, remove, save, getGoods } from '@/api/goods'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 0,
      page: 1,
      limit: 10,
      goodsQuery: {
        goodsNo: '',
        goodsName: '',
        begin: '',
        end: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      goods: {
        id: undefined,
        goodsNo: '',
        goodsName: '',
        price: '',
        gmtCreate: '',
        gmtModified: ''
      },
      dialogFormVisible: false,
      rules: {
        goodsNo: [{ required: true, message: '物品编号不能为空', trigger: 'blur' }],
        goodsName: [{ required: true, message: '物品名称不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '物品价格不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.page, this.limit, this.goodsQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.page = 1
      this.getList()
    },
    handleCreate() {
      this.resetGoods()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetGoods() {
      this.goods = {
        id: undefined,
        goodsNo: '',
        goodsName: '',
        price: '',
        gmtCreate: '',
        gmtModified: ''
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          save(this.goods).then((response) => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      getGoods(row.id).then((response) => {
        this.goods = response.data
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      })
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          save(this.goods).then((response) => {
            const index = this.list.findIndex(v => v.id === response.data.id)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      remove(row.id).then((response) => {
        this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['物品号', '物品名称', '价格', '创建时间', '修改时间']
        const filterVal = ['goodsNo', 'goodsName', 'price', 'gmtCreate', 'gmtModified']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '宿舍物品信息'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
